<?php

namespace app\api\controller;

use app\api\model\dealer\Setting;
use app\api\model\User as UserModel;
use app\api\model\Wxapp;
use app\common\library\wechat\WxUser;
use app\common\model\UserBankcard;
use app\common\model\UserCapital;
use app\common\model\UserGrade;
use app\common\model\Withdraw;
use app\common\service\qrcode\User as UserQrcode;
/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $model = new UserModel;
        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken()
        ]);
    }

    public function phoneLogin()
    {
        $model = new UserModel;
        $user_id = $model->phoneLogin($this->request->post());
        if($user_id){
            return $this->renderSuccess([
                'user_id' =>$user_id,
                'token' => $model->getToken()
            ]);
        }else{
            return $this->renderError('参数错误');
        }

    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        if($userInfo['grade_id'] < 6){
            $user_grade = UserGrade::where(['grade_id'=>$userInfo['grade_id']+1])->find();
            $upgrade = json_decode($user_grade['upgrade'],true);
            $grade['surplus'] = $upgrade['expend_money'] - $userInfo['expend_money'];
            $grade['name'] = $user_grade['name'];
        }else{
            $grade['surplus'] = 0;
            $grade['name'] = '最高等级';
        }

        return $this->renderSuccess(compact('userInfo','total','today','withdrawn','grade'));
    }
    public function edit()
    {
        $user = $this->getUser();
        $model = UserModel::detail1($user['user_id']);
        if ($model->edit($this->request->post())) {
            return $this->renderSuccess([], '更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
    /**
     * 获取推广二维码
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function poster()
    {
        //$this->user = $this->getUser();
        $Qrcode = new UserQrcode( $this->getUser());
        $setting = Setting::getAll();

        return $this->renderSuccess([
            // 二维码图片地址
            'qrcode' => $Qrcode->getImage(),
            // 页面文字
           // 'words' => $setting['words']['values'],
        ]);
    }
    /**
     * 获取手机号
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="iv", type="integer", required=true, description="")

     * @ApiParams   (name="encryptedData", type="integer", required=true, description="")

     * @ApiParams   (name="code", type="integer", required=true, description="")



     */
    public function getPhone() {
        $iv = $this->request->post("iv", '', 'trim');
        $encryptedData = $this->request->post("encryptedData", '', 'trim');
        $code = $this->request->post('code');
        if (!$iv || !$encryptedData) {
            return  $this->renderError('传参有误');
        }
        $wxConfig = Wxapp::getWxappCache();
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        $wxsession = $WxUser->sessionKey($code);
        $errCode = $this->decryptData($encryptedData, $iv, $data, $wxsession['session_key'], $wxConfig['app_id']);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {
                return   $this->renderSuccess(['phone'=>$result['phoneNumber']]);
            } else {
                return  $this->renderError('号码获取失败');
            }
        } else {
            return $this->renderError('用户信息更新失败');
        }
    }
    public function decryptData($encryptedData, $iv, &$data, $sessionKey, $appid) {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41003;
        }
        $data = $result;
        return 0;
    }

    public function myTeam(){
        $userInfo = $this->getUser();
        $UserModel = new UserModel();
        $key = $this->request->param("key", '');
        $grade_id = $this->request->param("grade_id", '');
        if($key){
            $where['nickName|phone'] = ['like', '%' . trim($key) . '%'];
        }
        if($grade_id){
            $where['grade_id'] = $grade_id;
        }
        $where['referee_id'] = $userInfo['user_id'];
        $where['is_delete'] = 0;

       // $list= $UserModel->where($where)->order('create_time desc')->select();
        $list = $UserModel->where($where)->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
   //     $list= $UserModel->alias('u')->field('u.*')->join('user s','s.referee_id = u.user_id')->where($where)->order('u.create_time desc')->select();
        foreach ($list as &$value){
            if($key){
                $where1['nickName|phone'] = ['like', '%' . trim($key) . '%'];
            }
            if($value['grade_id'] == 0){
                $value['grade_name'] = '无级别';
            }else{
                $value['grade_name'] = UserGrade::where(['grade_id'=>$value['grade_id']])->value('name');
            }

//            $where1['referee_id'] = $value['user_id'];
//            $where1['is_delete'] = 0;
//            $value['list'] = $UserModel->where($where1)->order('create_time desc')->select();
//            foreach ( $value['list'] as &$v){
//                $v['grade_name'] = UserGrade::where(['grade_id'=>$v['grade_id']])->value('name');
//            }
        }
        return $this->renderSuccess([
            'list' => $list,
            'info' => $userInfo
        ]);
    }

    public function commissionLog(){
        $userInfo = $this->getUser();
        $UserCapital = new UserCapital();
        $UserModel = new UserModel();
        $where['user_id'] = $userInfo['user_id'];
        $date = $this->request->param("date", '');

        if($date){
            //$date_arr = explode('-',$date);
            $start = strtotime("$date".'-01');
            $end = date("Y-m-d", strtotime("+1 months", $start));
//            $start = $date_arr[0];
//            $end = $date_arr[1];
            if($start && $end){//between
                $start_time = $start;
                $end_time = strtotime($end);
                $where['create_time'] = ['between',"$start_time,$end_time"];
            }
        }



    //    $list= $UserCapital->where($where)->order('create_time desc')->select();
        $list = $UserCapital->where($where)->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
   //     $list= $UserModel->alias('u')->field('u.*')->join('user s','s.referee_id = u.user_id')->where($where)->order('u.create_time desc')->select();
        foreach ($list as &$value){
            $where1['user_id'] = $value['return_user_id'];
            $value['return_nick_name'] = $UserModel->where($where1)->value('nickName');
        }
        return $this->renderSuccess([
            'list' => $list,
            'info' => $userInfo
        ]);
    }

    public function addBankcard(){
        $userInfo = $this->getUser();
        $UserBankcard = new UserBankcard();
        $post =  $this->request->request();
        if (empty($post)) {
            return $this->renderError( '参数错误');
        }
        if(isset($post['id']) && $post['id'] != ''){

            $bankcard = $UserBankcard->where(['id'=>$post['id']])->find();
            if (empty($bankcard)) {
                return $this->renderError( '参数错误');
            }
            $data['name'] = $post['name'];
            $data['number'] = $post['number'];
            $data['deposit'] = $post['deposit'];
            $data['phone'] = $post['phone'];
            $UserBankcard->where('id',$post['id'])->setField($data);
            return $this->renderSuccess([], '添加成功');
        }else{
            $bankcard = $UserBankcard->where(['user_id'=>$userInfo['user_id'],'number'=>$post['number']])->find();
            if (!empty($bankcard)) {
                return $this->renderError( '银行卡已存在');
            }
            $data['create_time'] = time();
            $data['user_id'] = $userInfo['user_id'];
            $data['name'] = $post['name'];
            $data['number'] = $post['number'];
            $data['deposit'] = $post['deposit'];
            $data['phone'] = $post['phone'];
            $data['wxapp_id'] = 10001;
            $UserBankcard->insert($data);
            return $this->renderSuccess([], '添加成功');
        }

    }
    public function bankcardList(){
        $userInfo = $this->getUser();
        $UserBankcard = new UserBankcard();
        $where['user_id'] = $userInfo['user_id'];
        $list = $UserBankcard->where($where)->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
        return $this->renderSuccess([
            'list' => $list,
        ]);
    }

    public function delBankcard(){
        $userInfo = $this->getUser();
        $UserBankcard = new UserBankcard();
        $post =  $this->request->request();
        $where['user_id'] = $userInfo['user_id'];
        if(!$post['id']){
            return $this->renderError('参数错误');
        }
        $where['id'] = $post['id'];
        $ress = $UserBankcard->where($where)->find();
        if(empty($ress)){
            return $this->renderError('数据不存在');
        }
        $res = $UserBankcard->where($where)->delete();
        if($res){
            return $this->renderSuccess('删除成功');
        }else{
            return $this->renderError('删除失败');
        }
    }

    public function gradeList(){
        $list = UserGrade::where(['status'=>1])->field('grade_id,name')->select();
        return $this->renderSuccess($list);

    }

    public function policy(){
        //article_category
        $info = db('article')->where(['category_id'=>3])->order('create_time desc')->find();
        //article_content
        $info['article_content'] = htmlspecialchars_decode($info['article_content']);
        return $this->renderSuccess($info);
    }
    public function withdraw(){
        $userInfo = $this->getUser();
        $withdrawn_d = \app\common\model\Withdraw::where(['user_id'=> $userInfo['user_id'],'apply_status'=>['in','10,20,40']])->sum('money');//待提现佣金
        $userInfo['balance'] =$userInfo['balance'] - $withdrawn_d;
        return $this->renderSuccess($userInfo);

    }
}
